package com.hai.prism.utils;

public class ByteAndInt {

    /**
     * 整型转byte数组
     *
     * @param i     整数
     * @param isBig true:大端模式  false:小端模式
     * @return 数组
     */
    public static byte[] intToByteArray(int i, boolean isBig) {
        byte[] result = new byte[4];
        // 由高位到低位
        if (isBig) {
            result[0] = (byte) ((i >> 24) & 0xFF);
            result[1] = (byte) ((i >> 16) & 0xFF);
            result[2] = (byte) ((i >> 8) & 0xFF);
            result[3] = (byte) (i & 0xFF);
        } else {
            result[3] = (byte) ((i >> 24) & 0xFF);
            result[2] = (byte) ((i >> 16) & 0xFF);
            result[1] = (byte) ((i >> 8) & 0xFF);
            result[0] = (byte) (i & 0xFF);
        }
        return result;
    }
 
    /**
     * byte数组转整型
     *
     * @param bytes byte数组
     * @param start 起始位
     * @param isBig true:大端模式  false:小端模式
     * @return 整数
     */
    public static int byteArrayToInt(byte[] bytes, int start, boolean isBig) {
        int value = 0;
        if (isBig) {
            value += (bytes[start] & 0x000000FF) << 24;
            value += (bytes[start + 1] & 0x000000FF) << 16;
            value += (bytes[start + 2] & 0x000000FF) << 8;
            value += (bytes[start + 3] & 0x000000FF);
        } else {
            value += (bytes[start] & 0x000000FF);
            value += (bytes[start + 1] & 0x000000FF) << 8;
            value += (bytes[start + 2] & 0x000000FF) << 16;
            value += (bytes[start + 3] & 0x000000FF) << 24;
        }
        return value;
    }

}
